<?php

namespace app\api\model;
use think\facade\Log;
use think\Db;

class HttpMachine
{
    public static function SendWashCammand($machineno,$action)
    {
        $machine = Db::table('machine')->where("machine_no",$machineno)->find();
        if(!$machine){
            Log::record("$machineno machine is empty SendWashCammand-err-".$re);
            return 0;
        }
        
        $re = self::SendWashPost($machineno,$action,$machine['machine_type_id'],$machine['imei']);
        $workstatus=json_decode($re,true);
        if($workstatus['success']==1){
            return 1;
        }
        Log::record("$machineno $action SendWashCammand-err- $re");
        return  0;
    }

    public static function GetMachineWorkStatus($machineno) 
    {
        //判断机器所属类型
        $machine = Db::table('machine')->where("machine_no",$machineno)->find();
        if(!$machine){
            Log::record("$machineno workstatus GetMachineWorkStatus-err-".$re);
            return "";
        }

        if($machine["machine_type_id"] == 1){
            $re=self::SendWashPost($machineno,"workstatus",$machine['machine_type_id'],$machine['imei']);
            $workstatus=json_decode($re,true);
            if($workstatus['success']==1){
                return $workstatus['data']['runningstatus'];
            }
            Log::record("$machineno workstatus GetMachineWorkStatus-err-".$re);
            return "";
        }else{
            //直接查询数据库了
            //心跳是否ok
            if( (time() - 120) >= $machine['last_heart'])
            {
                return "-1";
            }
            //状态是否ok
            if($machine["status"] === 0){
                return "1";
            }
            
            return "";

        }
        
    }


    public static function SendWashPost($machineno,$action,$machine_type_id,$imei) 
    {
        if($machine_type_id == 1){
            $machine_action =$action;
            $url="http://v1.webapi.cooleasy.net/WasherApi";
            $token="e21edcc33d4141e1a43d4a2611bf35a4";
            $timestamp=time();
            $sign=self::GetMachineSign($machineno,$machine_action);
            $parammap = array(
                            "action" => $machine_action,
                            "machineSn" => $machineno,
                            "sign" => $sign,
                            "timeStamp" =>  $timestamp,
                            "token" => $token
                        );
            $re = self::send_post($url,$parammap);
              //array(3) { ["success"]=> int(1) ["msg"]=> string(2) "ok" ["data"]=> array(6) { ["online"]=> string(1) "1" ["runningstatus"]=> string(1) "1" ["runningprocess"]=> string(1) "0" ["runningprogram"]=> string(1) "0" ["remainingtime"]=> string(1) "0" ["faultflag"]=> string(0) "" } }
        }else{

            $map=[
                ['machine_type_id', '=', $machine_type_id],
                ['action', '=', $action]
            ];
            $machine_type_action = Db::table('machine_type_action')->where($map)->find();
            if(!$machine_type_action){
                return json_encode(['success'=>0,'error' => "$machineno machine_type_action $action is empty"]);
            }
            //$imei = $machine['imei'];
            $machine_action = $machine_type_action['machine_action'];
            //抵用 swoole  http://sme.chubangkj.com:9501/pushToImei?imei=机器码&do=指令
           // $timslock = self::lock(time()); &time=$timslock
            $p1 = urlencode($imei);
            $p2 = urlencode($machine_action);
            $url = "http://sme.chubangkj.com:9501/pushToImei?imei=$p1&do=$p2"; 
            //Log::record("$machineno $machine_action SendWashCammand- $url");
            $re = file_get_contents($url);
            //Log::record("$machineno $machine_action SendWashCammand- $re");
        }
        return $re;
      
    }

/**
     * 模拟POST与GET请求
     *
     * Examples:
     * ```
     * HttpCurl::request('http://example.com/', 'post', array(
     *  'user_uid' => 'root',
     *  'user_pwd' => '123456'
     * ));
     *
     * HttpCurl::request('http://example.com/', 'post', '{"name": "peter"}');
     *
     * HttpCurl::request('http://example.com/', 'post', array(
     *  'file1' => '@/data/sky.jpg',
     *  'file2' => '@/data/bird.jpg'
     * ));
     *
     * // windows
     * HttpCurl::request('http://example.com/', 'post', array(
     *  'file1' => '@G:\wamp\www\data\1.jpg',
     *  'file2' => '@G:\wamp\www\data\2.jpg'
     * ));
     *
     * HttpCurl::request('http://example.com/', 'get');
     *
     * HttpCurl::request('http://example.com/?a=123', 'get', array('b'=>456));
     * ```
     *
     * @param string $url [请求地址]
     * @param string $type [请求方式 post or get]
     * @param bool|string|array $data [传递的参数]
     * @param array $header [可选：请求头] eg: ['Content-Type:application/json']
     * @param int $timeout [可选：超时时间]
     *
     * @return array($body, $header, $status, $errno, $error)
     * - $body string [响应正文]
     * - $header string [响应头]
     * - $status array [响应状态]
     * - $errno int [错误码]
     * - $error string [错误描述]
     */
    public static function request($url, $type, $data = false, $header = [], $timeout = 0)
    {
        $cl = curl_init();
        // 兼容HTTPS
        if (stripos($url, 'https://') !== FALSE) {
            curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($cl, CURLOPT_SSLVERSION, 1);
        }
        // 设置返回内容做变量存储
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
        // 设置需要返回Header
        curl_setopt($cl, CURLOPT_HEADER, true);
        // 设置请求头
        if (count($header) > 0) {
            curl_setopt($cl, CURLOPT_HTTPHEADER, $header);
        }
        // 设置需要返回Body
        curl_setopt($cl, CURLOPT_NOBODY, 0);
        // 设置超时时间
        if ($timeout > 0) {
            curl_setopt($cl, CURLOPT_TIMEOUT, $timeout);
        }
        // POST/GET参数处理
        $type = strtoupper($type);
        if ($type == 'POST') {
            curl_setopt($cl, CURLOPT_POST, true);
            // convert @ prefixed file names to CurlFile class
            // since @ prefix is deprecated as of PHP 5.6
            if (class_exists('\CURLFile') && is_array($data)) {
                foreach ($data as $k => $v) {
                    if (is_string($v) && strpos($v, '@') === 0) {
                        $v = ltrim($v, '@');
                        $data[$k] = new \CURLFile($v);
                    }
                }
                // var_dump($data);
            }
            curl_setopt($cl, CURLOPT_POSTFIELDS, $data);
        }
        if ($type == 'GET' && is_array($data)) {
            if (stripos($url, "?") === FALSE) {
                $url .= '?';
            }
            $url .= http_build_query($data);
        }
        curl_setopt($cl, CURLOPT_URL, $url);
        // 读取获取内容
        $response = curl_exec($cl);
        // 读取状态
        $status = curl_getinfo($cl);
        // 读取错误号
        $errno  = curl_errno($cl);
        // 读取错误详情
        $error = curl_error($cl);
        // 关闭Curl
        curl_close($cl);
        if ($errno == 0 && isset($status['http_code'])) {
            $header = substr($response, 0, $status['header_size']);
            $body = substr($response, $status['header_size']);
            return array($body);//, $header, $status, 0, ''
        } else {
            return array('', '', $status, $errno, $error);
        }
    }

    public static function send_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
          'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 10 * 60 // 超时时间（单位:s）
          )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
      }

      public static function GetMachineSign($machineno,$action) 
      {
          $token="e21edcc33d4141e1a43d4a2611bf35a4";
          $appSecret="GFdsCY5T56uzTiE0zFka3fsmLCdFwjbf";
          $timestamp=time();
          $str = "{$appSecret}action={$action}machinesn={$machineno}timestamp={$timestamp}token={$token}";
          return strtoupper(md5($str));
      }




    //加密函数
    public static function lock($txt,$key='Swoole.sme')
    {
        $txt = $txt.$key;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0,64);
        $ch = $chars[$nh];
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
            $tmp .= $chars[$j];
        }
        return urlencode(base64_encode($ch.$tmp));
    }

    //解密函数
    public static function unlock($txt,$key='Swoole.sme')
    {
        $txt = base64_decode(urldecode($txt));
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars,$ch);
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = substr($txt,1);
        $tmp = '';
        $i=0;$j=0; $k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
            while ($j<0) $j+=64;
            $tmp .= $chars[$j];
        }
        return trim(base64_decode($tmp),$key);
    }




}
